package com.recsmile;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.concurrent.ImmediateEventExecutor;

/**
 * Created by Administrator on 2016/8/20.
 */
public class ChatSimpleChannelInboundHandler extends SimpleChannelInboundHandler {

    private static final ChannelGroup group  ;
    static{
        group = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
            throws Exception {

        if(evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE){
            //ctx.pipeline().remove(HttpRequestHandler.class);

            group.writeAndFlush(new TextWebSocketFrame("Client "+ctx.channel()+" joined!"));

            group.add(ctx.channel());
        }else{
            super.userEventTriggered(ctx, evt);
        }

    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
            group.writeAndFlush(((TextWebSocketFrame)msg).retain());
    }
}
